# 用户-角色绑定服务层
from backend.models.user_role import UserRole
from backend.models.role import Role
from backend.models.user import User
from backend.infrastructure.database import db

def get_user_roles(user_id):
    user_roles = UserRole.query.filter_by(user_id=user_id).all()
    role_ids = [ur.role_id for ur in user_roles]
    roles = Role.query.filter(Role.id.in_(role_ids)).all()
    return [r.to_dict() for r in roles]

def set_user_roles(user_id, role_ids):
    # 先删除原有绑定
    UserRole.query.filter_by(user_id=user_id).delete()
    # 批量添加新绑定
    for rid in role_ids:
        ur = UserRole(user_id=user_id, role_id=rid)
        db.session.add(ur)
    db.session.commit()
    return {'success': True}
